package cn.shadow.message;

import cn.shadow.bean.PlayerModule;
import cn.shadow.concurrent.DisruptorExecutor;
import cn.shadow.module.login.LoginModuleMessages;
import cn.shadow.moulde.ModuleHub;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

import static cn.shadow.utils.BufferUtil.readVarInt32;

@Slf4j
@Data
public class MessageWorker implements Worker {
    private static final long MAX_TIME_OUT = 20;
    /**
     * 信息传输通道
     */
    private ChannelSender channelSender;
    private long lastPingTime;

    private DisruptorExecutor taskExc;
    private MessageProcessor playerModule;

    private Scanner scanner = new Scanner(System.in);

    public MessageWorker(Channel channel, ModuleHub moduleHub) {
        this.channelSender = new ChannelSender(channel, moduleHub);
        lastPingTime = System.currentTimeMillis();
        taskExc = new DisruptorExecutor(1, 8192, "客户端线程");
        playerModule = new PlayerModule(moduleHub, channelSender);
    }


    private void disconnect(DisconnectReason reasonUnknown) {

    }

    @Override
    public void onConnected() {
        //开始发送登录消息
        System.out.println("请输入您的账号:");
        String username = scanner.nextLine();
        channelSender.sendMessage(LoginModuleMessages.requestLoginBuffer(username));
    }

    @Override
    public void onDisconnected() {

    }

    @Override
    public void onMessage(ByteBuf buffer) {
        ByteBuf copy = buffer.copy();
        int checkSumByte = copy.readUnsignedByte();
//        log.info("checkSumByte=" + checkSumByte);
        int offset = copy.readUnsignedByte();// 跳过offset
//        log.info("offset = " + offset);
        int moduleID = readVarInt32(copy); //模块id
        int sequenceID = readVarInt32(copy); //顺序id
        taskExc.processMessage(copy, moduleID, sequenceID, playerModule); //用户线程自己处理自己的事情
    }


}
